package com.zbmy.plugin.im.server.core.back.processor;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import io.netty.channel.Channel;

import com.alibaba.druid.util.StringUtils;
import com.base.framework.utils.JsonUtils;
import com.base.framework.utils.RedisUtils;
import com.zbmy.plugin.im.server.core.NetShareInstance;
import com.zbmy.plugin.im.server.core.packet.LoginPacket;
import com.zbmy.plugin.im.server.core.protocol.MessageHolder;
import com.zbmy.plugin.im.server.core.protocol.ProtocolHeader;
import com.zbmy.plugin.im.server.core.session.UserSessionManger;
import com.zbmy.plugin.im.server.spring.SpringUtil;

/**
 * 
 * 登录消息处理  
 * @ClassName: LoginMessageProcessor    
 * @author 杨乐平    
 * @date 2018年5月4日 下午3:03:21    
 * @version  v 1.0
 */
public class LoginMessageProcessor implements MessageProcessor {
	@Override
	public void excute(MessageHolder messageHolder) {
		// 执行登入操作
		String body = messageHolder.getBody();
		if(StringUtils.isEmpty(body)){
			// 登入失败
			return;
		}
		// 反序列化
		LoginPacket loginPacket = JsonUtils.readValue(body, LoginPacket.class);
		if(loginPacket == null){
			// 登入失败
			return;
		}
		Channel channel = messageHolder.getChannel();
		if(channel == null){
			// 登入失败
			return;
		}
		UserSessionManger.userToChannelOnlineMap.put(String.valueOf(loginPacket.getUserId()), channel);
		
		RedisUtils redisUtils = SpringUtil.getBean("redisUtils", RedisUtils.class);
		Map<String,Object> setValueMap = new HashMap<String, Object>();
		setValueMap.put("serverIp", NetShareInstance.serverIp);
		redisUtils.set(String.valueOf(loginPacket.getUserId()),  JsonUtils.writeValueAsString(setValueMap));
		String value = redisUtils.get(String.valueOf(loginPacket.getUserId()));
		
		// 测试
		/*boolean needSendTempateFlag = false;  // 是否需要发送模版消息
		// 短链接转发到别的服务器
		if(!StringUtils.isEmpty(value)){
			Map<String,Object> valueMap = JsonUtils.readValue(value, Map.class);
			if(valueMap != null){
				String serverIp=MapUtils.getString(valueMap, "serverIp");
				if(org.apache.commons.lang.StringUtils.isEmpty(serverIp) || !StringUtils.equals(serverIp,  NetShareInstance.serverIp)){
					needSendTempateFlag = true;
				}else{
					try {
						new MessageDispact().dispactToOtherServer(serverIp, messageHolder);
					} catch (Exception e) {
						needSendTempateFlag = true;
					}
				}
			}else{
				needSendTempateFlag = true;
			}
		}*/
		// 存储userId和当前服务器ID对应到redis
		MessageHolder responseMessageHolder = new MessageHolder();
		responseMessageHolder.setBody(body);
		responseMessageHolder.setChannel(channel);
		responseMessageHolder.setStatus(ProtocolHeader.STATUS_SUCCESS);
        responseMessageHolder.setSign(ProtocolHeader.SIGN_RESPONSE);
        responseMessageHolder.setType(ProtocolHeader.TYPE_LOGIN);
        //responseMessageHolder.setStatus(ProtocolHeader.SERVER_BUSY);
        responseMessageHolder.setBody("恭喜您，登录成功！");
        channel.writeAndFlush(responseMessageHolder);
	}
	
	protected void responseMsg(Channel channel, MessageHolder sessageHolder){
		try {
			String content = sessageHolder.getBody();
			 byte[] array = content.getBytes("UTF-8");
			 int byteLen = array.length;
			 ByteBuffer directBuffer = ByteBuffer.allocate(byteLen + 9);   // 这里一定要注意，分配得大小一定要等于数据占用大小
			 directBuffer.putShort(ProtocolHeader.MAGIC);
			 directBuffer.put(sessageHolder.getStatus());
			 directBuffer.put(sessageHolder.getSign());
			 directBuffer.put(sessageHolder.getStatus());
			 directBuffer.putInt(byteLen);
			 directBuffer.put(array);
			 channel.write(directBuffer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
